package com.scoutmobmap.server;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.persistence.Id;

import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;

import com.googlecode.objectify.Objectify;
import com.scoutmobmap.shared.OfferDto;

public class Offer {
  public static Offer addOffer(Objectify ofy, String id) {
    Offer offer = new Offer(id);
    if (offer.initialized) {
      ofy.put(offer);
      return offer;
    }
    return null;
  }
  
  @Id String id;
  private boolean initialized = false;
  public String url;
  
  public Date expiration;
  public Date start;
  public int numClaimed;
  public String vendorUrl;
  public String latlng;
  public String title;
  public String details;
  
  
  public Offer(String id) {
    this.id = id;
    initialize();
  }
  
  private Offer() {}
  
  public String getUrl() { return url; }
  
  private void initialize() {
    url = "http://www.scoutmob.com/san-francisco/deal/" + id;
    Document doc = Util.readAndParseUrl(this.url);
    String DATE_FORMAT = "mm/dd/yyyy";
    SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT);
    String expirationString = getText(doc, "div.expiration");
    try {
      expiration = dateFormat.parse(expirationString.replace("Expires:", "").trim());
    } catch (ParseException e) {
      expiration = new Date(0L);
      error("Failed to parse date");
    }
    start = new Date(0L);  // need from main page
    numClaimed = 0;  // need from main page
    vendorUrl = getText(doc, "a[name=website]");
    title = getText(doc, "div.title");
    details = getText(doc, "div.details").replaceAll("Can't combine offers.", "").trim();
    
    String mapUrl = doc.select("a[name=map]").first().attr("href");
    latlng = mapUrl.substring(mapUrl.indexOf('@') + 1);
    if ("".equals(latlng)) { error("Error parsing latlng"); }
    initialized = true;
  }
  
  private String getText(Document doc, String id) {
    String value = doc.select(id).first().text();
    if ("".equals(value)) { error("Could not find " + id); }
    return value;
  }
  
  private void error(String msg) {
    System.err.println("MINING FAILURE: ID: " + id + " " + msg);
  }
  
  public String toString() {
    StringBuilder sb = new StringBuilder("Offer");
    sb.append(" ID: " + id);
    sb.append(" Expiration: " + expiration);
    sb.append(" Details: " + details);
    sb.append(" LatLng: " + latlng);    
    sb.append(" Title: " + title);    
    return sb.toString();
  }
  
  public OfferDto toDto() {
    OfferDto toReturn = new OfferDto();
    toReturn.id = id;
    toReturn.expiration = expiration;
    toReturn.start = start;
    toReturn.numClaimed = numClaimed;
    toReturn.vendorUrl = vendorUrl;
    toReturn.latlng = latlng;
    toReturn.title = title;
    toReturn.details = details;
    return toReturn;
  }
}
